﻿using UnityEditor;
using UnityEditor.MemoryProfiler;
using UnityEngine;

namespace PerfAssist.MemoryProfilerAdvanced.Editor.PAContrib.TrackerModes
{
    public class TrackerMode_Remote : TrackerMode_Base
    {
        private bool _connectPressed;

        private string _IPField = MemConst.RemoteIPDefaultText;

        public override void OnEnter()
        {
            var saved = EditorPrefs.GetString(MemPrefs.LastConnectedIP);
            if (!string.IsNullOrEmpty(saved)) _IPField = saved;
        }

        public override void Update()
        {
            if (_connectPressed)
            {
                TrackerModeUtil.Connect(_IPField);
                _connectPressed = false;
            }
        }

        protected override void Do_GUI()
        {
            GUI.SetNextControlName("LoginIPTextField");
            var currentStr = GUILayout.TextField(_IPField, GUILayout.Width(100));
            if (!_IPField.Equals(currentStr)) _IPField = currentStr;

            if (GUI.GetNameOfFocusedControl().Equals("LoginIPTextField") &&
                _IPField.Equals(MemConst.RemoteIPDefaultText)) _IPField = "";

            var savedState = GUI.enabled;

            var connected = /*NetManager.Instance != null && NetManager.Instance.IsConnected &&*/
                MemUtil.IsProfilerConnectedRemotely;

            GUI.enabled = !connected;
            if (GUILayout.Button("Connect", GUILayout.Width(80))) _connectPressed = true;
            GUI.enabled = connected;
            if (GUILayout.Button("Take Snapshot", GUILayout.Width(100))) MemorySnapshot.RequestNewSnapshot();
            GUI.enabled = savedState;

            GUILayout.Space(DrawIndicesGrid(300, 20));
        }

        public override bool SaveSessionInfo(PackedMemorySnapshot packed)
        {
            var sessionName = _sessionTimeStr + TrackerModeConsts.RemoteTag + _IPField;
            return TrackerModeUtil.SaveSnapshotFiles(sessionName, _selected.ToString(), packed);
        }


        public override bool SaveSessionJson(CrawledMemorySnapshot Unpacked)
        {
            var sessionName = _sessionTimeStr + TrackerModeConsts.RemoteTag + _IPField;
            return TrackerModeUtil.SaveSnapshotJson(sessionName, _selected + ".json", Unpacked);
        }
    }
}